package com.xique.wxclient.controller;

import com.xique.common.core.constant.HttpStatus;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.wxclient.bean.domain.ParkCar;
import com.xique.wxclient.bean.domain.ParkInfo;
import com.xique.wxclient.bean.domain.User;
import com.xique.wxclient.bean.domain.Visitor;
import com.xique.wxclient.bean.request.WxAddVisitorRequest;
import com.xique.wxclient.bean.request.WxCancelVisitorRequest;
import com.xique.wxclient.bean.vo.UserParkVo;
import com.xique.wxclient.service.biz.service.IVisitorBizService;
import com.xique.wxclient.service.biz.service.IWxAuthService;
import com.xique.wxclient.service.biz.service.IWxClientCommandService;
import com.xique.wxclient.service.service.IParkCarService;
import com.xique.wxclient.service.service.IParkInfoService;
import com.xique.wxclient.service.service.IUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 微信接口
 * 暂时写，后面讨论规范一下
 */
@RestController
@RequestMapping("")
@Slf4j
public class WxClientController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IParkInfoService parkInfoService;

    @Autowired
    private IVisitorBizService visitorBizService;

    @Autowired
    private IWxClientCommandService wxClientCommandService;

    @Autowired
    private IParkCarService parkCarService;

    @Autowired
    private IWxAuthService wxAuthService;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    /**
     * 微信授权，获取手机号
     */
    @GetMapping("/auth")
    @ApiOperation("微信授权，返回授权信息给前端")
    public AjaxResult wxAuth(String js_code){
        return wxAuthService.wxAuth(js_code);
    }

    /**
     * 根据手机号获取用户小区列表和允许邀请访客类型
     * 1、根据手机号查询用户表，状态
     *  0禁用, 1启用
     */
    @GetMapping("/userPark/list")
    @ApiOperation("根据手机号获取用户小区列表和允许邀请访客类型")
    public AjaxResult userParkList(String phone)
    {
        if(StringUtils.isEmpty(phone)){
            return AjaxResult.error(HttpStatus.NO_CONTENT,"前端未登陆");
        }
        User user = new User();
        user.setPhone(phone);
        user.setStatus("1");
        //未删除
        user.setDelFlag(0);
        List<User> userList = userService.selectUserList(user);
        if(CollectionUtils.isEmpty(userList)){
            return AjaxResult.error("当前手机号未绑定小区，请联系管理员！");
        }
        List<UserParkVo> userParkVoList = new ArrayList<>(userList.size());
        UserParkVo userParkVo;
        ParkInfo parkInfo;
        for(User user1 : userList){
            userParkVo = new UserParkVo();
            userParkVo.setParkId(user1.getParkId());
            parkInfo = parkInfoService.selectParkInfoById(user1.getParkId());
            userParkVo.setParkCode(parkInfo.getCode());
            userParkVo.setParkName(parkInfo.getName());
            userParkVo.setUserId(user1.getId());
            String isVisitorCarType = StringUtils.isEmpty(user1.getVisitorCarType()) || user1.getVisitorCarType().contains("1") ? "no" : "yes";
            userParkVo.setIsVisitorCar(isVisitorCarType);
            String[] visitorCarTypes = StringUtils.isNotEmpty(user1.getVisitorCarType()) ? user1.getVisitorCarType().split(",") : new String[]{"1"};
            userParkVo.setVisitorCarTypes(visitorCarTypes);
            userParkVoList.add(userParkVo);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", userParkVoList);
        return AjaxResult.success("成功", map);
    }

    /**
     * {
     *     "phone": "18883701120",
     *     "parkId": 105,
     *     "parkCode": "1629194758116",
     *     "parkName": "研发岗亭测试车场",
     *     "userId": 7638,
     *     "date": "2021-10-09 00:00:00",
     *     "visitorName": "测试小刘",
     *     "visitorPhone": "18883701123",
     *     "visitorCarType": "2",
     *     "visitorCarPlate": "粤B98989"
     * }
     * 1、信息保存；（车辆表、访客表）
     * 2、访客车辆信息下发到设备；
     * 3、人脸暂不处理
     * TODO 1、车辆数据下发到设备；2、车场访客表增加车牌字段；3、访客记录添加到访客表中
     * @param request
     * @return
     */
    @PostMapping("/visitor/add")
    @ApiOperation("邀请访客信息提交")
    public AjaxResult addVisitor(@RequestBody WxAddVisitorRequest request){
        if(StringUtils.isEmpty(request.getPhone())){
            return AjaxResult.error(HttpStatus.NO_CONTENT,"前端未登陆");
        }
        log.info("邀请访客信息提交-请求参数：{}", request);
        User user = userService.selectUserById(request.getUserId());
        ParkCar downParkCar = new ParkCar();

        // 手动开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);

        try {
            ParkCar parkCar = visitorBizService.saveVisitorCar(request,user);
            log.info("邀请访客信息提交-存储访客车信息：{}", parkCar);
            if(null == parkCar){
                dataSourceTransactionManager.rollback(transactionStatus);
                return AjaxResult.error("访客车辆保存失败");
            }
            Visitor visitor = visitorBizService.saveVisitorInfo(request);
            log.info("邀请访客信息提交-存储访客信息：{}", visitor);
            if(null == visitor){
                dataSourceTransactionManager.rollback(transactionStatus);
                return AjaxResult.error("访客信息保存失败");
            }
            dataSourceTransactionManager.commit(transactionStatus);
            downParkCar = parkCar;
        } catch (Exception e) {
            dataSourceTransactionManager.rollback(transactionStatus);
            e.printStackTrace();
            log.error("邀请访客保存数据失败：{}", e.getMessage());
        }

        AjaxResult result = wxClientCommandService.downSingleCar(request.getParkId(), downParkCar);
        log.info("邀请访客信息提交-下发访客车信息结果：{}", result);
        return result;
    }

    /**
     * 我的访客列表
     * @param phone
     * @return
     */
    @GetMapping("/visitor/list")
    @ApiOperation("我的访客列表")
    public AjaxResult visitorList(String phone) {
        if(StringUtils.isEmpty(phone)){
            return AjaxResult.error(HttpStatus.NO_CONTENT,"前端未登陆");
        }
        log.info("我的访客列表-手机号：{}", phone);
        User user = new User();
        user.setPhone(phone);
        user.setStatus("1");
        //未删除
        user.setDelFlag(0);
        List<User> userList = userService.selectUserList(user);
        log.info("我的访客列表-用户列表：{}", userList);
        List<Visitor> visitorList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(userList)){
            List<Long> userIdsList = userList.stream().map(User::getId).collect(Collectors.toList());
            String userIds = StringUtils.join(userIdsList,",");
            log.info("我的访客列表-用户ids：{}", userIds);
            visitorList = visitorBizService.getVisitorList(userIds);
            log.info("我的访客列表-访客列表：{}", visitorList);
            visitorList.stream().forEach(item -> {
                ParkInfo parkInfo = parkInfoService.selectParkInfoById(item.getParkId());
                item.setParkName(parkInfo.getName());
            });
            log.info("我的访客列表-访客列表2：{}", visitorList);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", visitorList);
        log.info("我的访客列表-访客列表3：{}", visitorList);
        return AjaxResult.success("成功", map);
    }


    /**
     * 取消访客邀请
     * 1、删除访客车辆信息；
     * 2、修改访客状态；
     * 3、
     * @param request
     * @return
     */
    @PostMapping("/visitor/cancel")
    @ApiOperation("取消访客邀请")
    @Transactional
    public AjaxResult cancelVisitor(@RequestBody WxCancelVisitorRequest request){
        if(StringUtils.isEmpty(request.getPhone())){
            return AjaxResult.error(HttpStatus.NO_CONTENT,"前端未登陆");
        }
        Visitor visitor = visitorBizService.cancelVisitor(request);
        //车牌不为空的话，要删除车辆
        if(null != visitor && StringUtils.isNotEmpty(visitor.getVisitorCarPlate())){
            ParkCar parkCar = new ParkCar();
            parkCar.setParkId(request.getParkId());
            parkCar.setPlate(visitor.getVisitorCarPlate());
            List<ParkCar> parkCarList = parkCarService.selectParkCarList(parkCar);
            if(!CollectionUtils.isEmpty(parkCarList)){
                ParkCar parkCar1 = parkCarList.get(0);
                parkCarService.deleteParkCarById(parkCar1.getId());
                return wxClientCommandService.delSingleCar(request.getParkId(),parkCar1);
            }else{
                return AjaxResult.success("删除成功");
            }
        }else{
            return AjaxResult.success("删除成功");
        }
    }
}
